package com.liqi.frame.comm.controller.monitor;

import cn.hutool.core.net.NetUtil;
import com.liqi.frame.comm.dto.HttpResult;
import com.liqi.frame.comm.po.*;
import com.liqi.frame.comm.util.AddressUtil;
import com.liqi.frame.comm.util.ArithUtil;
import com.liqi.frame.comm.util.ShiroUtil;
import org.apache.shiro.session.Session;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.CentralProcessor.TickType;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.lang.reflect.MalformedParameterizedTypeException;
import java.net.InetAddress;
import java.util.*;

/**
 * 监控的ajax
 * @author liqi on 2020/1/18 0018. liqiwork@qq.com
 */
@RestController
@RequestMapping("/monitor/ajax")
public class ServerAjaxController {

    /**
     * 获取服务器信息
     * @return
     * @throws Exception
     */
    @RequestMapping({"getServerInfo"})
    @ResponseBody
    public HttpResult getServerInfo() throws Exception{
        Collection<Session> sessionList = ShiroUtil.getActiveSessions();
        for (Session session:sessionList) {
//            session.setAttribute();
        }
//        AddressUtil.getRealAddressByIP("218.76.52.42");

        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();

        Cpu cpu = new Cpu();
        CentralProcessor centralProcessor= hal.getProcessor();
        long[] prevTicks = centralProcessor.getSystemCpuLoadTicks();

        Util.sleep(1000);
        long[] ticks = centralProcessor.getSystemCpuLoadTicks();
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        Long cpuSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        Long cpuUsed = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        Long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        Long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        Long totalCpu = cpuUsed + nice + cpuSys + idle + iowait + irq + softirq + steal;
//        cpu核数
        cpu.setCpuNum(centralProcessor.getLogicalProcessorCount());
        cpu.setTotal(totalCpu.doubleValue());
//        系统使用率
        cpu.setSys(cpuSys.doubleValue());
//        用户使用率
        cpu.setUsed(cpuUsed.doubleValue());
        cpu.setWait(iowait.doubleValue());
//        当前空闲率
        cpu.setFree(idle.doubleValue());

        Mem mem = new Mem();
        GlobalMemory memory = hal.getMemory();
        mem.setTotal(memory.getTotal());
        mem.setUsed(memory.getTotal() - memory.getAvailable());
        mem.setFree(memory.getAvailable());

        Properties props = System.getProperties();
        Jvm jvm = new Jvm();
        jvm.setTotal(Runtime.getRuntime().totalMemory());
        jvm.setMax(Runtime.getRuntime().maxMemory());
        jvm.setFree(Runtime.getRuntime().freeMemory());
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setHome(props.getProperty("java.home"));

        Sys sys = new Sys();
        sys.setComputerName(InetAddress.getLocalHost().getHostName());
        sys.setComputerIp(InetAddress.getLocalHost().getHostAddress());
        sys.setOsName(props.getProperty("os.name"));
        sys.setOsArch(props.getProperty("os.arch"));
        sys.setUserDir(props.getProperty("user.dir"));


        List<SysFile> sysFiles = new LinkedList<SysFile>();
        OperatingSystem os = si.getOperatingSystem();
        FileSystem fileSystem = os.getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            SysFile sysFile = new SysFile();
            sysFile.setDirName(fs.getMount());
            sysFile.setSysTypeName(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(convertFileSize(total));
            sysFile.setFree(convertFileSize(free));
            sysFile.setUsed(convertFileSize(used));
            sysFile.setUsage(ArithUtil.mul(ArithUtil.div(used, total, 4), 100));
            sysFiles.add(sysFile);
        }

        Map resultMap = new HashMap<>();
        resultMap.put("cpu", cpu);
        resultMap.put("mem", mem);
        resultMap.put("jvm", jvm);
        resultMap.put("sys", sys);
        resultMap.put("sysFiles", sysFiles);

        return HttpResult.success(resultMap);
    }

    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    public String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb)
        {
            return String.format("%.1f GB", (float) size / gb);
        }
        else if (size >= mb)
        {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        }
        else if (size >= kb)
        {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        }
        else
        {
            return String.format("%d B", size);
        }
    }
}
